class MyPromise {
    constructor(executor) {
        //状态值，状态只能由 pending 变为 fulfilled， 或由pending 变为 rejected，一旦改变状态，一直保持
        this.status = 'pending'
        //接收值
        this.value = 'undefined'
        //成功的函数队列
        this.onResolvedCallBacks = []
        //失败的函数队列
        this.onRejectedClassbacks = []

        //成功时的方法
        let resolve = data => {
            if (this.status === 'pending') {
                this.value = data
                this.status = 'fulfilled'
                this.onResolvedCallBacks.forEach(callback=> callback(this.value))
            }
        }


        //失败时的方法
        let reject = err => {
            if (this.status === 'pending') {
                this.value = err
                this.status = 'rejected'
                this.onRejectedClassbacks.forEach(callback => callback(this.value))
            }
        }

        //executor 方法执行
        try {
            executor(resolve, reject)
        } catch (error) {
            //执行出错，rejected调用
            reject(error)
        }
    }

    //then 调用
    then(onResolved, onRejected) {
        if (this.status === 'pending') {
            //等待状态，添加回调函数到成功的函数队列
            this.onResolvedCallBacks.push(() => {
                onResolved(this.value)
            })
            //等待状态，添加回调函数到失败的函数队列
            this.onRejectedClassbacks.push(() => {
                onRejected(this.value)
            })
        } else if (this.status === 'fulfilled') {
            //调用成功，把值返回
            onResolved(this.value)
        } else if (this.status === 'rejected') {
            //调用失败
            onRejected()
        }
    }


}


/*
 测试函数
*/
function fn() {
    return new MyPromise((resolve, reject) => {
        setTimeout(() => {
            let randomNum = Math.random() 
            if (randomNum > 0.6) {
                resolve(1)
            } else {
                reject(2)
            }
        }, 1000)
    })
}

fn().then(res => {
    console.log({ res });
}, err => {
    console.log({ err });
})
